#include "SchmidtCAM.h"

int main( int argc, char *argv[] ){

    int opt = -1;

    if( argc != 2 && argc != 4 ){
        printf("> usage: %s ad9508.ini\n", argv[0]);
        printf("> or \n");
        printf("> usage: %s ad9508.ini reg_addr reg_data\n", argv[0]);
        return 0;
    }

    if( argc == 2 )
        opt = 1;
    else if( argc == 4 )
        opt = 2;

    char cfg_ini[1024];
    sprintf(cfg_ini, "%s", argv[1]);
    
    char reg_addr[8];
    uint32_t reg_data;

    if( opt == 2 ){
        sprintf(reg_addr, "%s", argv[2]);
        reg_data = (uint32_t)(atoi(argv[3]));
    }


    int fd = open("/dev/mem", O_RDWR | O_SYNC);
    uint *ptr1 = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, ADDR_GPIO_OUT);
    uint *gpio_reg      = ptr1;     // 0x41200000
    uint *gpio2_reg     = ptr1+2;   // 0x41200008
    
    uint *ptr2 = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, ADDR_GPIO_IN);
    uint *gpio_in_reg   = ptr2;     // 0x41210000

    // SPI config
    SPI_CONFIG *spi_config = (SPI_CONFIG*)malloc(sizeof(SPI_CONFIG));

    setup_SPI_by_device_name( spi_config, "ad9508" );

    AD9508_Config *ad9508_cfg = (AD9508_Config*)malloc(sizeof(AD9508_Config));
    init_ad9508_config( ad9508_cfg );

    read_ad9508_config( ad9508_cfg, cfg_ini, "AD9508" );

    // print_ad9508_config( ad9508_cfg );

    if( opt == 1 ){
        config_ad9508_via_SPI(  gpio_reg,
                                gpio2_reg,
                                gpio_in_reg,
                                spi_config,
                                ad9508_cfg );
    } else if ( opt == 2 ){
        config_a_ad9508_reg_via_SPI(    gpio_reg,
                                        gpio2_reg,
                                        gpio_in_reg,
                                        spi_config,
                                        ad9508_cfg,
                                        reg_addr,
                                        reg_data );
    }    

    free(ad9508_cfg);
    free(spi_config);
    
    
    sync_ad9508( gpio_reg );    // sync outputs
    

    munmap(ptr1,10);
    munmap(ptr2,10);
    close(fd);

    return 0;
}
